// import { ThemedText } from '@/components/ThemedText';
// import { useLocalSearchParams, useRouter } from 'expo-router';
// import React, { useEffect, useState } from 'react';
// import { View, Text, StyleSheet, TextInput, Button } from 'react-native';
// import { WebView } from 'react-native-webview';

// const App = () => {
//   const [getaddress, setAddress] = useState('');
//   const [locationma, setLocation] = useState(null);
//   const router = useRouter();

//   const { item } = useLocalSearchParams<{ item: string }>();
//   const parseItem = JSON.parse(decodeURIComponent(item));
//   const dizhi = parseItem.location;

//   useEffect(() => {
//     // console.log('11111111');
//     setAddress(dizhi);
//     geocodeAddress();
//   }, []);

//   const geocodeAddress = async () => {
//     try {
//       const apiKey = '139830430391b31454abad3a8771fee0';
//       console.log(getaddress, 'getaddress');

//       const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(getaddress)}&key=${apiKey}`;

//       const response = await fetch(url);
//       const data = await response.json();

//       if (data.status === '1' && data.geocodes.length > 0) {
//         console.log(data.status, 'status');
//         console.log(data.geocodes.length, 'kength');


//         const { location } = data.geocodes[0];
//         const [longitude, latitude] = location.split(',');
//         setLocation({ longitude, latitude });
//       } else {
//         console.log(data, '地理位置获取失败');
//         // alert('地理位置获取失败');
//       }
//     } catch (error) {
//       console.error('地理编码失败:', error);
//     }
//   };

//   return (
//     <View style={{ flex: 1 }}>
//       <TextInput
//         style={{ height: 40, borderColor: '#ccc', borderWidth: 1, marginBottom: 10, paddingLeft: 8 }}
//         placeholder="请输入地址"
//         value={getaddress}
//         onChangeText={setAddress}
//       />
//       <Button title="获取经纬度" onPress={geocodeAddress} />

//       {locationma && (
//         // <View>

//         <WebView
//           originWhitelist={['*']}
//           source={{
//             html: `
//               <html>
//                 <head>
//                   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
//                   <script src="https://webapi.amap.com/maps?v=1.4.15&key=139830430391b31454abad3a8771fee0"></script>
//                   <style>
//                     body, html { margin: 0; padding: 0; height: 100%;background:'pink'; }
//                   </style>
//                 </head>
//                 <body>
//                   <div id="container" style="width: 100%; height: 100%;"></div>
//                   <script>
//                     var map = new AMap.Map('container', {
//                       center: [${locationma.longitude}, ${locationma.latitude}],
//                       zoom: 10
//                     });
//                   </script>
//                 </body>
//               </html>
//             `,
//           }}
//           style={{ flex: 1 }}
//         />
//         // </View>
//       )}
//     </View>
//   );
// };

// export default App;
import { ThemedText } from '@/components/ThemedText';
import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TextInput, Button } from 'react-native';
import { WebView } from 'react-native-webview';

const App = () => {
  const [getaddress, setAddress] = useState('');
  const [locationma, setLocation] = useState(null);
  const router = useRouter();

  const { item } = useLocalSearchParams<{ item: string }>();
  const parseItem = JSON.parse(decodeURIComponent(item));
  const dizhi = parseItem.location;

  useEffect(() => {
    setAddress(dizhi);
    geocodeAddress();
  }, []);

  const geocodeAddress = async () => {
    try {
      const apiKey = '139830430391b31454abad3a8771fee0';
      console.log(getaddress, 'getaddress');

      const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(getaddress)}&key=${apiKey}`;

      const response = await fetch(url);
      const data = await response.json();

      if (data.status === '1' && data.geocodes.length > 0) {
        console.log(data.status, 'status');
        console.log(data.geocodes.length, 'kength');

        const { location } = data.geocodes[0];
        const [longitude, latitude] = location.split(',');
        setLocation({ longitude, latitude });
      } else {
        console.log(data, '地理位置获取失败');
        // alert('地理位置获取失败');
      }
    } catch (error) {
      console.error('地理编码失败:', error);
    }
  };

  return (
    <View style={{ flex: 1 }}>
      <TextInput
        style={{ height: 40, borderColor: '#ccc', borderWidth: 1, marginBottom: 10, paddingLeft: 8 }}
        placeholder="请输入地址"
        value={getaddress}
        onChangeText={setAddress}
      />
      <Button title="点击查看地图   " onPress={geocodeAddress} />

      {locationma && (
        <WebView
          originWhitelist={['*']}
          source={{
            html: `
              <html>
                <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                  <script src="https://webapi.amap.com/maps?v=1.4.15&key=139830430391b31454abad3a8771fee0"></script>
                  <style>
                    body, html { margin: 0; padding: 0; height: 100%; background: 'pink'; }
                  </style>
                </head>
                <body>
                  <div id="container" style="width: 100%; height: 100%;"></div>
                  <script>
                    var map = new AMap.Map('container', {
                      center: [${locationma.longitude}, ${locationma.latitude}],
                      zoom: 20
                    });

                    // 添加标记
                    var marker = new AMap.Marker({
                      position: [${locationma.longitude}, ${locationma.latitude}],
                      title: '目标地址'
                    });

                    map.add(marker);
                  </script>
                </body>
              </html>
            `,
          }}
          style={{ flex: 1 }}
        />
      )}
    </View>
  );
};

export default App;